#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4
"""
    @author join.kang
"""
import datetime
from datetime import timedelta
import os
import cPickle
from rest_framework import permissions, status
from rest_framework.response import Response
import rsa
from cvirt.manager.views import NonModelBaseAPIView
from cvirt.common import utils
from cvirt.common import translate as _
from cvirt.manager.models import Instance
from cvirt.manager.views import NamedAPIViewMixIn
from cvirt.manager.views import ExpiringTokenAuthentication2
from cvirt import version

class PlatformView(NamedAPIViewMixIn, NonModelBaseAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    authentication_classes = (ExpiringTokenAuthentication2,)

    def _get(self, request, *args, **kwargs):
        hardwareid = utils.hardware_uuid()
        try:
            with file("/etc/licenseinfo") as key:
                licenseinfo = self._decrypt_license(key.read())
        except:
            result = {"name": "Tcloud", "version": version.version, "total": 0, "available": 0,
                      "validity": "license不存在", "hardwareid": hardwareid,'build':version.build}
            return Response(result)

        insts = Instance.objects.count()
        available = licenseinfo["inst"] - insts
        #just check time period

        if licenseinfo['time'] != -1 and datetime.datetime.now().date() > licenseinfo['time']:
            validity = "认证序列号已过期"
        elif available <= 0:
            validity = "允许创建的实例已满"
        else:
            validity = licenseinfo["time"]
        return Response({"name": "Tcloud", "version": version.version, "total": licenseinfo["inst"],
                         "available": available, "validity": validity, "hardwareid": hardwareid,
                         'build':version.build}, status=status.HTTP_200_OK)

    def _decrypt_license(self, emsg):
        dmsg = rsa.transform.binascii.a2b_hex(emsg)
        with file(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tcloudpriv')) as prikeyfile:
            dmsg = rsa.decrypt(dmsg, rsa.PrivateKey.load_pkcs1(prikeyfile.read()))
        return cPickle.loads(dmsg)

    def update_license(self, request, *args, **kwargs):
        result = {}
        licenseinfo = request.DATA.get("licenseinfo",None)
        insts = Instance.objects.all()
        try:
            license = self._decrypt_license(licenseinfo)
            if license['time'] != -1 and (datetime.datetime.now().date() + timedelta(1)) > license['time']:
                return Response({"msg": "更新失败,序列号已过期"})
            if license['hardwareid'] != utils.hardware_uuid():
                return Response({"msg": "不识别的硬件设备"})
            available = license["inst"] - len(insts)
            if available < 0:
                return Response({"msg": "非法序列号"})

            result = {"status": 200, "total": license["inst"], "available": available, "validity": license['time']}
        except:
            return Response(_("非法序列号"), status=status.HTTP_400_BAD_REQUEST)

        f = file("/etc/licenseinfo", "w")
        f.write(licenseinfo)
        f.close()
        return Response(result)

    def register_license(self, request, *args, **kwargs):
        result = {}
        licenseinfo = request.DATA.get("licenseinfo",None)
        try:
            license = self._decrypt_license(licenseinfo)
            if license['time'] != -1 and datetime.datetime.now().date() > license['time']:
                return Response({"msg": "序列号已过期"})
            insts = Instance.objects.all()
            available = license["inst"] - len(insts)
            result = {"status": 200, "total": license["inst"], "available": available, "validity": license['time']}
        except:
            return Response(_("非法序列号"), status=status.HTTP_400_BAD_REQUEST)

        f = file("/etc/licenseinfo", "w")
        f.write(licenseinfo)
        f.close()
        return Response(result)